package com.asura.qqeffect.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;

/**
 * Created by Asura on 2016/12/8.
 */

public class SlidingView extends View {
    private int touchSlop;
    private int maximumFlingVelocity;
    private int minimumFlingVelocity;
    private VelocityTracker velocityTracker;

    public SlidingView(Context context) {
        super(context);
        init(context);
    }

    private void init(Context context) {
        velocityTracker = VelocityTracker.obtain();
        ViewConfiguration viewConfiguration = ViewConfiguration.get(context);
        touchSlop = viewConfiguration.getScaledTouchSlop();
        maximumFlingVelocity = viewConfiguration.getScaledMaximumFlingVelocity();
        minimumFlingVelocity = viewConfiguration.getScaledMinimumFlingVelocity();
    }

    public SlidingView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SlidingView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    int lastX, lastY;

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        velocityTracker.addMovement(event);
        int x = (int) event.getRawX();
        int y = (int) event.getRawY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                int dx = x - lastX;
                int dy = y - lastY;
                setTranslationX(getTranslationX() + dx);
                setTranslationY(getTranslationY() + dy);
                break;
            case MotionEvent.ACTION_UP:
                velocityTracker.computeCurrentVelocity(1000, maximumFlingVelocity);
                float xVelocity = velocityTracker.getXVelocity();
                float yVelocity = velocityTracker.getYVelocity();
                if ((minimumFlingVelocity <= xVelocity && xVelocity <= maximumFlingVelocity)
                        || (yVelocity <= maximumFlingVelocity && yVelocity >= minimumFlingVelocity)){

                }
                break;
        }
        lastX = x;
        lastY = y;
        return super.onTouchEvent(event) || true;
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        return super.dispatchTouchEvent(event);
    }
}
